package com.dataimport.service.impl;

import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dataimport.entity.sourceentity.StudentCourseInfo;
import com.dataimport.entity.targetentity.Course;
import com.dataimport.mapper.CourseMapper;
import com.dataimport.mapper.StudentCourseInfoMapper;
import com.dataimport.service.CourseService;
import com.dataimport.utils.HasNullFieldUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;
@Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course>implements CourseService {
    @Autowired
    private StudentCourseInfoMapper studentCourseInfoMapper;
    private final long PAGE_SIZE=100;
    private int  pageCurrent=1;
    @Override
    public void dealWithCourse() {
        for (;pageCurrent>0;pageCurrent++) {
            DynamicDataSourceContextHolder.push("mysql2");
//            分页
            IPage<StudentCourseInfo> iPage = new Page<>();
            iPage.setSize(PAGE_SIZE);
            iPage.setCurrent(pageCurrent);
            IPage<StudentCourseInfo> studentCourseInfoPage = studentCourseInfoMapper.selectPage(iPage, null);
            // 进行拆解封装
            List<StudentCourseInfo> studentCourseInfoList = studentCourseInfoPage.getRecords();
            List<Course> courses = studentCourseInfoList.stream().parallel().map(studentCourseInfo -> {
                Course course = new Course();
                course.setCourseCode(studentCourseInfo.getKcbm());
                course.setCourseName(studentCourseInfo.getKcmc());
                course.setCourseCredit(studentCourseInfo.getXf());
//                course.setTeachHours(Long.parseLong(studentCourseInfo.getJsxs()));
//                course.setExperimentHours(Long.parseLong(studentCourseInfo.getSyxs()));
//                course.setOtherHours(Long.parseLong(studentCourseInfo.getQtxs()));
                course.setDepartmentId(studentCourseInfo.getYxsh());
                return course;
            }).collect(Collectors.toList());
            courses.forEach(System.out::println);
            DynamicDataSourceContextHolder.poll();
            insertCourse(courses);
            if(studentCourseInfoPage.getTotal()-studentCourseInfoPage.getSize()*studentCourseInfoPage.getCurrent()<=0){
                break;
            }
        }
    }

    //插入数据
    @Transactional(rollbackFor = Exception.class)
    public void insertCourse(List<Course> courses){
        //开启数据库
        DynamicDataSourceContextHolder.push("mysql1");
        this.saveBatch(courses);
        DynamicDataSourceContextHolder.poll();
    }
}
